require('dotenv').config()
// 导入数据库操作模块
const db = require('../../db')

// MARK 权限点管理

// MARK GET / sys / permission	获取权限点列表
exports.getList = (req, res) => {
  // 查询权限点数据
  const query = `
    SELECT 
        id,
        name,
        description,
        type,
        code,
        pid,
        enVisible
    FROM 
        permission
  `

  db.query(query, (err, results) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10031, message: '查询权限点失败', error: err.message })
    }

    // 格式化响应数据
    const data = results.map(row => ({
      id: row.id,
      name: row.name,
      description: row.description,
      type: row.type,
      code: row.code,
      pid: row.pid,
      enVisible: row.enVisible
    }))

    res.json({
      success: true,
      code: 10000,
      data: data,
      message: '获取权限点成功'
    })
  })
}
// MARK POST / sys / permission	新增权限点
exports.addNew = (req, res) => {
  const { name, description, type, code, pid, enVisible } = req.body

  // 验证输入数据
  if (!name || !description || !type || !code || pid === undefined || enVisible === undefined) {
    return res.status(400).json({ success: false, code: 10045, message: '必要字段不能为空' })
  }

  // 校验权限点名字是否重复
  const checkNameQuery = `
    SELECT 
        id
    FROM 
        permission
    WHERE 
        name = ? AND pid = ?
  `

  db.query(checkNameQuery, [name, pid], (err, nameResults) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10046, message: '校验权限点名字失败', error: err.message })
    }

    if (nameResults.length > 0) {
      return res.status(400).json({ success: false, code: 10047, message: '权限点名字已存在' })
    }

    // 校验权限标识是否唯一
    const checkCodeQuery = `
      SELECT 
          id
      FROM 
          permission
      WHERE 
          code = ?
    `

    db.query(checkCodeQuery, [code], (err, codeResults) => {
      if (err) {
        return res.status(500).json({ success: false, code: 10048, message: '校验权限标识失败', error: err.message })
      }

      if (codeResults.length > 0) {
        return res.status(400).json({ success: false, code: 10049, message: '权限标识已存在' })
      }

      // 插入权限点信息
      const insertQuery = `
        INSERT INTO permission (name, description, type, code, pid, enVisible)
        VALUES (?, ?, ?, ?, ?, ?)
      `

      db.query(insertQuery, [name, description, type, code, pid, enVisible], (err, result) => {
        if (err) {
          return res.status(500).json({ success: false, code: 10050, message: '新增权限点失败', error: err.message })
        }

        const newId = result.insertId

        res.json({
          success: true,
          code: 10000,
          data: { id: newId.toString() },
          message: '新增权限点成功'
        })
      })
    })
  })
}
// MARK GET / sys / permission / { id }	获取权限点详情
exports.getById = (req, res) => {
  const { id } = req.params

  // 验证输入数据
  if (!id) {
    return res.status(400).json({ success: false, code: 10035, message: '权限点ID不能为空' })
  }

  // 查询权限点信息
  const query = `
    SELECT 
        id,
        name,
        description,
        type,
        code,
        pid,
        enVisible
    FROM 
        permission
    WHERE 
        id = ?
  `

  db.query(query, [id], (err, results) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10036, message: '查询权限点失败', error: err.message })
    }

    if (results.length === 0) {
      return res.status(404).json({ success: false, code: 10037, message: '权限点不存在' })
    }

    const permission = results[0]

    // 格式化响应数据
    const data = {
      id: permission.id,
      name: permission.name,
      description: permission.description,
      type: permission.type,
      code: permission.code,
      pid: permission.pid,
      enVisible: permission.enVisible
    }

    res.json({
      success: true,
      code: 10000,
      data: data,
      message: '获取权限点详情成功'
    })
  })
}
// MARK PUT / sys / permission / { id }	修改权限点详情
exports.putById = (req, res) => {
  const { id } = req.params
  const { name, description, type, code, pid, enVisible } = req.body
  // MARK 维护初始数据
  if (id <= 16) {
    return res.status(200).json({ success: false, code: 10066, message: '初始数据不可操作' })
  }
  // 验证输入数据
  if (!name || !description || !type || !code || pid === undefined || enVisible === undefined) {
    return res.status(400).json({ success: false, code: 10038, message: '必要字段不能为空' })
  }

  // 校验权限点名字是否重复（不包含自己）
  const checkNameQuery = `
    SELECT 
        id
    FROM 
        permission
    WHERE 
        name = ? AND id != ?
  `

  db.query(checkNameQuery, [name, id], (err, nameResults) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10039, message: '校验权限点名字失败', error: err.message })
    }

    if (nameResults.length > 0) {
      return res.status(400).json({ success: false, code: 10040, message: '权限点名字已存在' })
    }

    // 校验权限标识是否唯一（不包含自己）
    const checkCodeQuery = `
      SELECT 
          id
      FROM 
          permission
      WHERE 
          code = ? AND id != ?
    `

    db.query(checkCodeQuery, [code, id], (err, codeResults) => {
      if (err) {
        return res.status(500).json({ success: false, code: 10041, message: '校验权限标识失败', error: err.message })
      }

      if (codeResults.length > 0) {
        return res.status(400).json({ success: false, code: 10042, message: '权限标识已存在' })
      }

      // 更新权限点信息
      const updateQuery = `
        UPDATE permission
        SET 
            name = ?,
            description = ?,
            type = ?,
            code = ?,
            pid = ?,
            enVisible = ?
        WHERE 
            id = ?
      `

      db.query(updateQuery, [name, description, type, code, pid, enVisible, id], (err, result) => {
        if (err) {
          return res.status(500).json({ success: false, code: 10043, message: '更新权限点信息失败', error: err.message })
        }

        if (result.affectedRows === 0) {
          return res.status(404).json({ success: false, code: 10044, message: '权限点不存在' })
        }

        res.json({
          success: true,
          code: 10000,
          data: { id: id.toString() },
          message: '更新权限点信息成功'
        })
      })
    })
  })
}
// MARK DELETE / sys / permission / { id }	删除权限点
exports.delById = (req, res) => {
  const { id } = req.params
  // MARK 维护初始数据
  if (id <= 16) {
    return res.status(200).json({ success: false, code: 10066, message: '初始数据不可操作' })
  }
  // 验证输入数据
  if (!id) {
    return res.status(400).json({ success: false, code: 10032, message: '权限点ID不能为空' })
  }

  // 删除权限点信息
  const deleteQuery = `
    DELETE FROM permission
    WHERE 
        id = ?
  `

  db.query(deleteQuery, [id], (err, result) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10033, message: '删除权限点失败', error: err.message })
    }

    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, code: 10034, message: '权限点不存在' })
    }

    res.json({
      success: true,
      code: 10000,
      data: { id: id.toString() },
      message: '删除权限点成功'
    })
  })
}